<template>
    <div>
        <div>
            <el-card class="box">
                <!-- 搜索筛选区域 -->
                <div class="flex">
                    <div class="two">用户名称</div>
                    <div class="time_top">创建时间</div>
                </div>
                <div class="block_center"></div>
                <!-- 搜索输入区域 -->
                <div class="flexBox">
                    <div>
                        <el-input v-model="inputed" @input="filters" placeholder="输入内容" class="two">
                            <template #prefix>
                                <el-icon class="el-input__icon">
                                    <search />
                                </el-icon>
                            </template>
                        </el-input>
                    </div>
                    <!-- 日期范围选择器 -->
                    <div style="margin-left: 20px;">
                        <el-date-picker class="two" @change="data_filters" v-model="time" type="daterange"
                            range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" />
                    </div>
                </div>
                <div class="block_center"></div>
                <div class="block_center"></div>

                <!-- 操作按钮和筛选选项 -->
                <div class="option">
                    <div style="margin-top:0px;">
                        <!-- 快捷按钮筛选 -->
                        <el-badge class="button_left">
                            <el-button type="primary" size="default" style="height:35px;">
                                导出
                            </el-button>
                        </el-badge>
                        <el-badge class="button_lefts">
                            <el-button size="default" style="height:35px" :type="whole" @click="filts(0)">全部</el-button>
                        </el-badge>
                        <el-badge :value="Unpaid" class="button_left">
                            <el-button size="default" :type="lefts" class="button_filter"
                                @click="filtstt(1)">待付款</el-button>
                        </el-badge>
                        <el-badge :value="Paid" class="button_left">
                            <el-button size="default" :type="rights" class="button_filter"
                                @click="filtstt(2)">已付款</el-button>
                        </el-badge>
                        <el-badge :value="Verification" class="button_left">
                            <el-button size="default" :type="prima" class="button_filter"
                                @click="filtstt(3)">已核销</el-button>
                        </el-badge>
                        <el-badge :value="Canceled" class="button_left">
                            <el-button size="default" :type="closet" class="button_filter"
                                @click="filtstt(4)">已取消</el-button>
                        </el-badge>
                    </div>
                    <div>
                    </div>
                </div>

                <!-- table表格数据展示 -->
                <el-table :data="tableData.slice((currentPage - 1) * pageSize, currentPage * pageSize)"
                    style="width: 100%" :cell-style="{ 'text-align': 'center' }" ref="multipleTableRef" height="auto"
                    v-el-table-infinite-scroll="handleTableScroll" :header-cell-style="{ 'text-align': 'center' }"
                    stripe @selection-change="handleSelectionChange">
                    <el-table-column type="selection" width="55" />
                    <el-table-column prop="id" label="序号" width="70" fixed />
                    <el-table-column prop="title" label="景区名称" width="150" fixed>
                    </el-table-column>
                    <el-table-column prop="name" label="用户名称" width="150">
                        <template #default="scope">
                            {{ scope.row.name == '' || scope.row.name == null ? '暂无昵称' : scope.row.name }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="code" width="190" label="订单号" show-overflow-tooltip>
                    </el-table-column>
                    <el-table-column prop="monye" sortable width="140" label="总价格">
                        <template #default="scope">
                            {{ scope.row.money == '' || scope.row.money == null ? '暂无手机号' : scope.row.money }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="num" sortable label="总数量" width="140" />
                    <el-table-column prop="status" label="状态" width="140">
                        <template #default="scope">
                            <p
                                :style="{ color: scope.row.status == 1 ? 'rgba(255, 165, 0, 1)' : scope.row.status == 2 ? 'rgba(64, 158, 255, 1)' : scope.row.status == 3 ? 'rgba(124, 252, 0, 1)' : scope.row.status == 4 ? 'rgba(128, 128, 128, 1)' : scope.row.status }">
                                {{
                                    scope.row.status == 1 ? '待付款' : scope.row.status == 2 ? '待使用' : scope.row.status == 3 ?
                                        '已使用' : scope.row.status == 4 ? '已取消' : scope.row.status
                                }}</p>
                        </template>
                    </el-table-column>
                    <el-table-column prop="paytime" min-width="120" label="购买时间" fixed="right" show-overflow-tooltip>
                    </el-table-column>
                </el-table>

                <!-- 分页控件 -->
                <div class="paging">
                    <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
                        :page-sizes="[5, 10, 15, 20]" :small="small" :disabled="disabled" background
                        layout="total, sizes, prev, pager, next, jumper" :total="tableData.length" />
                </div>
            </el-card>
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { Search } from '@element-plus/icons-vue'
import { Scenic_order } from '../../../api/scien_order/index'
import { inject } from 'vue'
import '../../../style/all.css'//全局css
// 前缀域名全局
const testFn = inject('testFn')
testFn()
const testName = inject('testName')

// 登录存储起来的个人账户信息，为了拿token值
const tokens = JSON.parse(localStorage.getItem('tokens'));
console.log(tokens);

// 获取当前时间字符串
function getCurrentDateTimeString() {
    const now = new Date();
    // 获取当前的年份，并只取后两位
    const year = now.getFullYear().toString().slice();
    // 获取当前的月份，并确保是两位数（从0开始）
    const month = (now.getMonth() + 1).toString().padStart(2, '0');
    // 获取当前的日期，并确保是两位数
    const day = now.getDate().toString().padStart(2, '0');
    // 获取当前的小时，并确保是两位数
    const hours = now.getHours().toString().padStart('0');
    // 获取当前的分钟，并确保是两位数
    const minutes = now.getMinutes().toString().padStart(2, '0');
    // 获取当前的秒，并确保是两位数
    const seconds = now.getSeconds().toString().padStart(2, '0');
    // 拼接成所需的字符串格式
    const dateTimeString = `${year}-${month}-${day} ${hours}-${minutes}-${seconds}`;
    g = `${year}-${month}-${day}`
    return dateTimeString;
}

// 当前时间
let date = new Date();
// 获取当前时间
let date_time = `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()} ${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}`
console.log(Date.parse(new Date(date_time)));

// 原始数据
const Data = ref([])

// 各状态角标计数
const Unpaid = ref('0') // 未支付角标
const Paid = ref('0') // 已支付角标
const Canceled = ref('0') // 已取消角标
const Verification = ref('0') // 已核销角标

// 表格数据
const tableData = ref([])

// 页面加载时初始化数据
onMounted(() => {
    data()
})

const arrAll = ref([])
const indexoff = ref([])

// 请求列表数据渲染
const data = () => {
    Scenic_order({
        token: tokens.token,
        uid: tokens.userinfo.id
    }, {
        userid: tokens.userinfo.id
    }).then(res => {
        console.log(res);
        if (res.code == 1) {
            arrAll.value = res.data
            indexoff.value = res.data
            let arr = []
            let set = []
            let cancen = []
            let array_q = []

            // 处理返回的数据，计算各状态数量并添加额外字段
            for (let i = 0; i < res.data.length; i++) {
                // 未支付角标
                if (res.data[i].status == 1) {
                    arr.push(res.data[i])
                    Unpaid.value = arr.length
                }
                // 已支付角标
                if (res.data[i].status == 2) {
                    set.push(res.data[i])
                    Paid.value = set.length
                }
                // 已核销
                if (res.data[i].status == 3) {
                    cancen.push(res.data[i])
                    Verification.value = cancen.length
                }
                // 已取消
                if (res.data[i].status == 4) {
                    array_q.push(res.data[i])
                    Canceled.value = array_q.length
                }

                // 处理图片路径和状态标识
                res.data[i].imgs = testName + res.data[i].userImg
                if (Date.parse(new Date(date_time)) < Date.parse(new Date(res.data[i].over_time))) {
                    res.data[i].sheng = '生效中'
                } else {
                    res.data[i].sheng = '未生效'
                }
                if (res.data[i].status == '1') {
                    res.data[i].shen = '未支付'
                } else {
                    res.data[i].shen = '已支付'
                }
            }

            // 更新表格数据并执行搜索
            Data.value = res.data;
            tableData.value = res.data;
            OrderAll.value = tableData.value.length
            searh()
        } else {
            OrderAll.value = 0
        }
    })
}

// 搜索输入
const inputed = ref('')

// 分类名称搜索
function filters() {
    console.log(inputed.value);
    let a = [];

    // 根据输入内容筛选表格数据
    tableData.value = Data.value.filter(item => {
        // 判断是否满足搜索条件
        if (String(item.title).indexOf(String(inputed.value)) > -1) {
            return tableData.value;
        }
    });

    // 重置页码并重新计算各状态数量
    currentPage.value = 1
    let arrs = []
    let sets = []
    let cancens = []
    let array = []

    // 赋值为了下面选项卡筛选准备上次结果
    search_data.value = tableData.value

    // 计算筛选后各状态的数量
    for (let k = 0; k < tableData.value.length; k++) {
        // 未支付角标
        if (tableData.value[k].status == 1) {
            arrs.push(tableData.value[k])
            console.log(arrs);
            Unpaid.value = arrs.length
        } else if (tableData.value[k].status !== 1 || tableData.value[k].status !== 3) {
            Unpaid.value = arrs.length
        }

        if (tableData.value[k].status == 2) {
            sets.push(tableData.value[k])
            Paid.value = sets.length
        } else if (tableData.value[k].status !== 2) {
            Paid.value = sets.length
        }

        if (tableData.value[k].status == 3) {
            array.push(tableData.value[k])
            Verification.value = array.length
        } else if (tableData.value[k].status !== 3) {
            Verification.value = array.length
        }

        // 取消角标
        if (tableData.value[k].status == 4) {
            cancens.push(tableData.value[k])
            Canceled.value = cancens.length
        } else if (tableData.value[k].status !== 4) {
            Canceled.value = cancens.length
        }

        // 计算生效状态
        if (Date.parse(new Date(date_time)) < Date.parse(new Date(tableData.value[k].over_time))) {
            usable.value++
        } else {
            nousable.value++
        }
    }

    // 更新总数并处理空数据情况
    OrderAll.value = tableData.value.length
    tableData.value = tableData.value
    if (tableData.value == "") {
        Paid.value = '0'
        Unpaid.value = '0'
        Canceled.value = '0'
        Verification.value = '0'
    }
}

// 日期搜索
const data_filters = () => {
    let end_time
    let start_time
    let ars = []

    // 处理日期范围
    if (time.value) {
        end_time = Date.parse(new Date(time.value[0]))
        start_time = Date.parse(new Date(time.value[1]))
    }

    // 根据日期范围筛选表格数据
    tableData.value = Data.value.filter((item) => {
        if (item.title ?
            item.title.indexOf(inputed.value) > -1 &&
            (time.value ?
                Date.parse(new Date(`${item.createtime}`)) > end_time &&
                Date.parse(new Date(` ${item.createtime}`)) < start_time : true
            ) : true
        ) {
            return item
        }
        ars.push(item)
    });

    // 重新计算各状态数量
    let arrs = []
    let sets = []
    let cancens = []
    let array = []

    // 赋值为了下面选项卡筛选准备上次结果
    search_data.value = tableData.value

    // 计算筛选后各状态的数量
    for (let k = 0; k < tableData.value.length; k++) {
        // 未支付角标
        if (tableData.value[k].status == 1) {
            arrs.push(tableData.value[k])
            Unpaid.value = arrs.length
        } else if (tableData.value[k].status !== 1 || tableData.value[k].status !== 3) {
            Unpaid.value = arrs.length
        }

        if (tableData.value[k].status == 2) {
            sets.push(tableData.value[k])
            Paid.value = sets.length
        } else if (tableData.value[k].status !== 2) {
            Paid.value = sets.length
        }

        if (tableData.value[k].status == 3) {
            array.push(tableData.value[k])
            Verification.value = array.length
        } else if (tableData.value[k].status !== 3) {
            Verification.value = array.length
        }

        // 取消角标
        if (tableData.value[k].status == 4) {
            cancens.push(tableData.value[k])
            Canceled.value = cancens.length
        } else if (tableData.value[k].status !== 4) {
            Canceled.value = cancens.length
        }

        // 计算生效状态
        if (Date.parse(new Date(date_time)) < Date.parse(new Date(tableData.value[k].over_time))) {
            usable.value++
        } else {
            nousable.value++
        }
    }

    // 更新总数并处理空数据情况
    OrderAll.value = tableData.value.length
    tableData.value = tableData.value
    if (tableData.value == "") {
        Paid.value = '0'
        Unpaid.value = '0'
        Canceled.value = '0'
        Verification.value = '0'
    }
}

// 表格选择处理
const multipleTableRef = ref()
const SelectArr = ref([])

// 表格选择变化处理函数
const handleSelectionChange = (val) => {
    SelectArr.value = val
    console.log(SelectArr.value);
}

// 分页相关变量
const pageSize = ref(5);  // 每页显示条数
const currentPage = ref(1);  // 当前页码

// 搜索相关变量
const search_name = ref('')  // 用户名搜索
const search_tel = ref('')  // 手机号搜索
const time = ref('')  // 时间搜索
const search_data = ref()  // 搜索后数据

// 统计数据
const OrderAll = ref('0')  // 全部的徽章数量
const usable = ref(0)  // 生效中数量
const nousable = ref(0)  // 未生效数量

// 按钮状态控制
const whole = ref('primary')  // 全部按钮状态
const lefts = ref('')  // 待付款按钮状态
const rights = ref('')  // 已付款按钮状态
const prima = ref('')  // 已核销按钮状态
const closet = ref('')  // 已取消按钮状态

// 综合搜索
const searh = () => {
    // 重置分页和统计
    currentPage.value = 1
    usable.value = 0
    nousable.value = 0

    let end_time
    let start_time

    // 处理日期范围
    if (time.value) {
        end_time = Date.parse(new Date(time.value[0]))
        start_time = Date.parse(new Date(time.value[1]))
    }

    // 根据多种条件筛选表格数据
    tableData.value = Data.value.filter((item) => {
        if (item.name ?
            item.name.indexOf(search_name.value) > -1 &&
            item.tel.indexOf(search_tel.value) > -1 &&
            (time.value ?
                Date.parse(new Date(`${item.create_year}-${item.create_month}-${item.create_date} ${item.create_time}`)) > end_time &&
                Date.parse(new Date(`${item.create_year}-${item.create_month}-${item.create_date} ${item.create_time}`)) < start_time : true
            ) : true
        ) {
            return item
        }
    });

    // 重新计算各状态数量
    let arrs = []
    let sets = []
    let cancens = []
    let arrsr = []

    // 赋值为了下面选项卡筛选准备上次结果
    search_data.value = tableData.value

    // 计算筛选后各状态的数量
    for (let k = 0; k < tableData.value.length; k++) {
        // 未支付角标
        if (tableData.value[k].status == 1) {
            arrs.push(tableData.value[k])
            Unpaid.value = arrs.length
        } else if (tableData.value[k].status !== 1 || tableData.value[k].status !== 3) {
            Unpaid.value = arrs.length
        }

        if (tableData.value[k].status == 2) {
            sets.push(tableData.value[k])
            Paid.value = sets.length
        } else if (tableData.value[k].status !== 2) {
            Paid.value = sets.length
        }

        // 取消角标
        if (tableData.value[k].status == 4) {
            cancens.push(tableData.value[k])
            Canceled.value = cancens.length
        } else if (tableData.value[k].status !== 4) {
            Canceled.value = cancens.length
        }

        if (tableData.value[k].status == 3) {
            arrsr.push(tableData.value[k])
            Verification.value = arrsr.length
        } else if (tableData.value[k].status !== 3) {
            Verification.value = arrsr.length
        }

        // 计算生效状态
        if (Date.parse(new Date(date_time)) < Date.parse(new Date(tableData.value[k].over_time))) {
            usable.value++
        } else {
            nousable.value++
        }
    }

    // 更新总数并处理空数据情况
    OrderAll.value = tableData.value.length
    tableData.value = tableData.value
    if (tableData.value == "") {
        Paid.value = '0'
        Unpaid.value = '0'
        Canceled.value = '0'
        Verification.value = '0'
    }
}

// 状态筛选
const filtstt = (i) => {
    console.log(i);

    // 更新按钮状态
    if (i == '1') {
        whole.value = ''
        lefts.value = 'primary'
        rights.value = ''
        prima.value = ''
        closet.value = ''
    }
    else if (i == '2') {
        whole.value = ''
        lefts.value = ''
        prima.value = ''
        rights.value = 'primary'
        closet.value = ''
    } else if (i == '3') {
        whole.value = ''
        lefts.value = ''
        prima.value = 'primary'
        closet.value = ''
        rights.value = ''
    } else if (i == '4') {
        whole.value = ''
        lefts.value = ''
        prima.value = ''
        closet.value = 'primary'
        rights.value = ''
    }

    // 根据状态筛选数据
    let art = [];
    tableData.value = search_data.value.filter((item) => {
        // 判断是否满足搜索条件
        if (String(item.status).indexOf(String(i)) > -1) {
            return tableData
        }
    });

    console.log(tableData.value);
}

// 点击全部按钮
const filts = () => {
    currentPage.value = 1
    tableData.value = search_data.value

    // 更新按钮状态
    whole.value = 'primary'
    lefts.value = ''
    rights.value = ''
    closet.value = ''
    prima.value = ''
}
</script>

<style scoped>
.paging {
    display: flex;
    justify-content: center;
    margin-top: 10px;
}

.two {
    width: 220px
}
.button_lefts {
    margin-left: 100px;
}
.input {
    width: 220px;
    height: 36px;
    margin-right: 10px;
}

.button {
    width: 60px;
    height: 35px;
}

.search {
    width: 65%;
    display: flex;
    align-items: center;
    margin-bottom: 10px;
}

.flexBox {
    display: flex;
    width: 100%;
    align-items: center;
}

.option {
    margin-bottom: 10px;
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.badge {
    margin-right: 10px;
}

.el-date-range-picker__content {
    box-sizing: border-box;
    float: left;
    margin: 0;
    padding: 16px;
    width: 38%;
}
</style>